package com.tj.jinzao.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.VideoView;

import com.tj.jinzao.R;
import com.tj.jinzao.base.BaseActivity;

import butterknife.BindView;

/**
 * 播放视频页面
 * Created by wjy on 2019/1/5.
 */
public class VideoActivity extends BaseActivity implements MediaPlayer.OnPreparedListener {

    @BindView(R.id.videoView)
    VideoView mVideoView;

    private Dialog mDialog;

    public static void start(Context context, String url) {
        context.startActivity(new Intent(context, VideoActivity.class).putExtra("url", url));
    }

    @Override
    protected int getLeftButtonResId() {
        return R.mipmap.ic_back;
    }

    @Override
    public int getLayoutResource() {
        return R.layout.activity_video;
    }

    @Override
    protected void setupView() {
        super.setupView();
        String url = getIntent().getStringExtra("url");
        if (TextUtils.isEmpty(url)) {
            finish();
            return;
        }
        //设置视频控制器
        mVideoView.setMediaController(new MediaController(this));
        //播放完成回调
        mVideoView.setOnCompletionListener(new MyPlayerOnCompletionListener());
        mVideoView.setOnPreparedListener(this);
        //设置视频路径
        mVideoView.setVideoURI(Uri.parse(url));
        //开始播放视频
        mVideoView.start();
        showProgress(this);
    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        closeProgress();
    }

    class MyPlayerOnCompletionListener implements MediaPlayer.OnCompletionListener {

        @Override
        public void onCompletion(MediaPlayer mp) {
//            Toast.makeText(LocalVideoActivity.this, "播放完成了", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 网络连接时显示Loading
     */
    public void showProgress(Context context) {
        if (mDialog == null && context instanceof Activity) {
            try {
                mDialog = new Dialog(context, R.style.ThemeRequestDialog);
                mDialog.setContentView(new ProgressBar(context));
                mDialog.setCancelable(true);
                mDialog.setCanceledOnTouchOutside(false);
                mDialog.show();
            } catch (Exception e) {
            }
        }
    }

    public void closeProgress() {
        try {
            if (mDialog != null) {
                mDialog.dismiss();
                mDialog = null;
            }
        } catch (Exception e) {
        }
    }
}
